package com.bjsxt.chapter4_prototype;

/**
 * @ClassName Client4
 * @Description 测试原型模式创建对象的效率
 * @Author 黑马程序员
 * @Date 12:31 2024/6/21
 * @Version 1.0
 **/
public class Client4 {
    public static void main(String[] args) {
        int num = 1000;
        testNew(num);
        testClone(num);
        // new的方式耗时: 15767
        // clone的方式耗时: 15
    }

    // new的方式创建大量对象
    public static void testNew(int num) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            Laptop laptop = new Laptop();
        }
        long end = System.currentTimeMillis();

        System.out.println("new的方式耗时: " + (end - start));
    }

    // clone的方式创建大量对象
    public static void testClone(int num) {
        long start = System.currentTimeMillis();
        try {
            Laptop laptop = new Laptop();
            for (int i = 0; i < num; i++) {
                Laptop obj = (Laptop) laptop.clone();
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();

        System.out.println("clone的方式耗时: " + (end - start));
    }
}

// 笔记本电脑
class Laptop implements Cloneable{

    public Laptop() {
        try {
            // 模拟创还能对象耗时的过程
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
